﻿using System;
using System.Linq;
using PSE.Deployment.Engine;
using PSE.Deployment.Engine.Enums;
using PSE.Deployment.Engine.Interfaces;
using PSE.Deployment.SetupBase;
using PSE.Deployment.SetupBase.Configuration;
using PSE.Deployment.SetupBase.Configuration.Actions;
using PSE.Deployment.Util;
using Sinacor.Deployment.Setup.Main;

namespace Sinacor.Deployment.Setup.Wizard.Steps
{
    public class MSMQ : BaseStep
    {
        public StepNavigationAction NavigationAction { get; protected set; }
        private UI.MSMQ msmq;

        public MSMQ(IStepGroup parent)
            : base(parent)
        {
            this.Id = "MSMQ";

            this.ErrorBehavior = PSE.Deployment.Engine.Enums.StepErrorBehavior.NotifyParent;
            this.NavigationBehavior = PSE.Deployment.Engine.Enums.StepNavigationBehavior.NextPreviousCancel;

            this.ExecutionFinished += new EventHandler<PSE.Deployment.Engine.CustomEventArgs.ExecutionFinishedEventArgs>(MSMQ_ExecutionFinished);
        }

        void MSMQ_ExecutionFinished(object sender, PSE.Deployment.Engine.CustomEventArgs.ExecutionFinishedEventArgs e)
        {
            e.NavigationAction = this.NavigationAction;
        }

        public override void Execute()
        {
            Group msmqGroup = SetupMainFactory.GetInstance<SinacorMain>().Configuration.SystemInfo.Groups.SelectDeep(g => g.SubGroups).ToList().Find(g => g.Id == "MSMQ");

            if (msmqGroup != null)
            {
                foreach (ActionBase action in msmqGroup.Actions)
                {
                    if (action is InstallMessageQueue)
                    {
                        foreach (Queue queue in ((InstallMessageQueue)action).Queues)
                        {
                            msmq = new UI.MSMQ(queue);
                            msmq.ShowDialog();
                            this.NavigationAction = msmq.NavigationAction.GetValueOrDefault();
                        }
                    }
                }
            }
        }

        public override void Undo()
        {
            if (msmq != null)
                msmq.Close(false);
        }
    }
}
